﻿using System;
using System.Collections.Generic;
using System.Web;
using PayRoller.Code;
using System.Web.SessionState;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using HySoft.Cash.Business;
using HySoft.Cash.Structure;
using System.Configuration;
using System.Web.Profile;
using Huayou.UI.WebControls;
using Huayou.Utils;
using System.Data;
using HySoft.Cash.BaseClass;
using Huayou.Common;
using System.Net.Mail;
using PayRoller.UControls;
using HySoft.Cash;
using System.Runtime.Remoting.Messaging;
using System.Text;

namespace PayRoller.Manage
{
    public partial class PopupSendInvoice : ParentPage, IRequiresSessionState
    {
        private void SendMail(int invoiceID)
        {
            try
            {
                int pathPos = this.Request.Url.OriginalString.IndexOf(this.Request.Url.PathAndQuery);
                string domainString = this.Request.Url.OriginalString.Substring(0, pathPos);
                string invoiceGUID = InvoiceDic[invoiceID].Guid.ToString();
                string receiverMail = InvoiceDic[invoiceID].PreferredEmail;
                string orgName = InvoiceDic[invoiceID].OrgName;
                DateTime invoiceDate = InvoiceDic[invoiceID].InvoiceDate;
                int invoiceOverDueDays = AppSettings.InvoiceOverDueDays;
                DateTime invoiceDateTo = invoiceDate.AddDays(invoiceOverDueDays);

                string invoiceDetailsUrl = string.Format("{1}/manage/Invoices/InvoiceDetail.aspx?Guid={0}", invoiceGUID, domainString);
                string outputDir = HttpContext.Current.Server.MapPath("~/PDF/Invoice");

                string subject = "New Invoice from Golden Bridge";
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("Dear [{0}],", orgName);
                sb.AppendLine();
                sb.AppendLine();
                sb.AppendFormat("Please kindly find the attached invoice for the period from [{0}] to [{1}].", invoiceDate.ToString(AppSettings.DateFormatAU), invoiceDateTo.ToString(AppSettings.DateFormatAU));
                sb.AppendLine();
                sb.AppendLine();
                sb.AppendFormat("For further information please log onto your Payroller account by clicking on <a href=\"http://payroller.com.au/Login.aspx\">http://payroller.com.au/Login.aspx</a> or contact us at 1300 137 906.");
                sb.AppendLine();
                sb.AppendLine();
                sb.AppendLine("Best regards,");
                sb.AppendLine();
                sb.AppendLine("Customer Support Team");
                sb.AppendLine("Golden Bridge Payroller™");
                sb.AppendLine();
                sb.AppendLine("☎ 1300 137 906");
                sb.AppendLine("<FONT style=\"FONT-SIZE: 10pt; COLOR: #000; FONT-FAMILY: Webdings\">&Ecirc;</FONT> 1300 138 916 ");
                sb.AppendLine("✉ <A href=\"mailto:support@payroller.com.au\">support@payroller.com.au</a>");
                sb.AppendLine("<FONT style=\"FONT-SIZE: 10pt; COLOR: #000; FONT-FAMILY: Webdings\">ü</FONT><a href=\"http://www.payroller.com.au\"> www.payroller.com.au</a>");
                string body = sb.ToString();
                PDFAndMail.CreatePDFAndSendMail(invoiceDetailsUrl, outputDir, receiverMail, subject, body);
            }
            catch
            { }
        }

       

        protected void dgdList_DataBinding(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            string commandText = "";
            string str2 = "";
           

            //在账单日期+49天发送SendInvoice
            int invoiceSentDays = AppSettings.InvoiceSentDays;
            invoiceSentDays = -invoiceSentDays;
            commandText = "select i.Sid,i.OrgSid,i.SendStatus,InvoiceDate,(Principal + Interest+ PenaltyPaid + LateInterestChargesPaid) as InvoiceAmount,(PrincipalPaid + InterestPaid + PenaltyPaid + LateInterestChargesPaid) as  ReceiveAmount,Guid,i.IsValid,OrgName,o.PreferredEmail from tInvoiceList i inner join tOrgInfo o  on i.OrgSid=o.Sid where i.SendStatus="+ (int)InvoiceSendStatuses.NeedSend +" and i.IsValid!=" + (int)InvoiceStatuses.Deleted + " and InvoiceDate <= '" + SafeDateTime.LocalToday.AddDays(invoiceSentDays) + "' " + str2 + " order by i.Sid desc";

            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["SQLConnString"], CommandType.Text, commandText).Tables[0];
            CommonBasePage.SetPage(this.dgdList, dt);
            base.AddValue("pageno", Convert.ToString((int)(this.dgdList.CurrentPageIndex + 1)));
            this.txtParamstr.Text = base.PackPart(base.ParamValue);
        }

        /// <summary>
        /// 发票ID，发票字典
        /// </summary>
        private Dictionary<int, TinvoicelistDT> InvoiceDic
        {
            get
            {
                if (this.ViewState["InvoiceDic"] == null)
                {
                    this.ViewState["InvoiceDic"] = new Dictionary<int, TinvoicelistDT>();
                }

                return this.ViewState["InvoiceDic"] as Dictionary<int, TinvoicelistDT>;
            }
            set
            {
                this.ViewState["InvoiceDic"] = value;
            }
        }

        protected void dgdList_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            ListItemType itemType = e.Item.ItemType;
            if (itemType == ListItemType.Item || itemType == ListItemType.SelectedItem || itemType == ListItemType.AlternatingItem)
            {
                DataRowView drv = e.Item.DataItem as DataRowView;
                if (drv != null)
                {
                    int tempInvoiceID = Convert.ToInt32(drv["Sid"]);
                    if (InvoiceDic.ContainsKey(tempInvoiceID) == false)
                    {
                        TinvoicelistDT invoiceDT = TinvoicelistDT.ConvertFrom(drv.Row);
                        InvoiceDic.Add(tempInvoiceID, invoiceDT);
                    }

                    Literal litInvoiceDue = e.Item.FindControl("litInvoiceDue") as Literal;
                    if (litInvoiceDue != null)
                    {
                       int invoiceOverDueDays= AppSettings.InvoiceOverDueDays;
                       litInvoiceDue.Text = Convert.ToDateTime(drv["InvoiceDate"]).AddDays(invoiceOverDueDays).ToString(AppSettings.DateFormatAU);
                    }

                    LinkButton libSendStatus = e.Item.FindControl("libSendStatus") as LinkButton;
                    if (libSendStatus != null)
                    {
                        libSendStatus.CommandArgument = tempInvoiceID.ToString();
                        InvoiceSendStatuses sendStatus = (InvoiceSendStatuses)Convert.ToInt32(drv["SendStatus"]);
                        if (sendStatus == InvoiceSendStatuses.NeedSend || sendStatus == InvoiceSendStatuses.NeedReSend)
                        {
                            libSendStatus.Text = "Send";
                        }
                        else
                        {
                            libSendStatus.Text = "ReSend";
                        }
                    }
                }
            }
        }

        protected void dgdList_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            this.dgdList.CurrentPageIndex = e.NewPageIndex;
            this.dgdList.DataBind();
        }

        protected override void OnInit(EventArgs e)
        {
            base.m_ModuleCode = "0008";
            base.CheckLogin(true);
            base.CheckPerm();
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //this.btnSend.Attributes["onclick"] = "return sendit(this.form)";
            if (!this.Page.IsPostBack)
            {
                base.ParamValue = base.UnPack();
                this.txtParamstr.Text = base.PackPart(base.ParamValue);
                string str = base.GetValue("pageno");
                if (str != null)
                {
                    this.dgdList.CurrentPageIndex = Convert.ToInt32(str) - 1;
                }
                this.dgdList.DataBind();
            }
            else
            {
                base.ParamValue = base.UnPackPart(this.txtParamstr.Text);
            }
        }

        // Properties
        protected HttpApplication ApplicationInstance
        {
            get
            {
                return this.Context.ApplicationInstance;
            }
        }

        protected DefaultProfile Profile
        {
            get
            {
                return (DefaultProfile)this.Context.Profile;
            }
        }

        protected void dgdList_ItemCreated(object sender, DataGridItemEventArgs e)
        {
            ListItemType listItemType = e.Item.ItemType;
            if (listItemType == ListItemType.Item || listItemType == ListItemType.AlternatingItem)
            {
                LinkButton libSendStatus = e.Item.FindControl("libSendStatus") as LinkButton;
                if (libSendStatus != null)
                {
                    libSendStatus.Click += new EventHandler(libSendStatus_Click);
                }
            }
        }

        void libSendStatus_Click(object sender, EventArgs e)
        {
            int invoiceID = 0;
            LinkButton t = sender as LinkButton;
            if (t != null)
            {
                int.TryParse(t.CommandArgument, out invoiceID);
            }

            if (invoiceID > 0)
            {
                SendMail(invoiceID);

                using (TinvoicelistBN invoiceBN = new TinvoicelistBN(this.Page))
                {
                    TinvoicelistDT invoiceDT = invoiceBN.Get(invoiceID);
                    invoiceDT.SendStatus = InvoiceSendStatuses.Sent;
                    invoiceBN.Edit(invoiceDT);
                }

                this.dgdList.DataBind();
            }
        }
    }
}